#include "Readfile.h"
#include "ScamperHandler.h"

#include <map>
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>

/**
 * router graph inferred by MERLIN
 */
std::vector<Router *> router_vector;

 
int main(int argc, char ** argv)
{
	if ( argc != 4 )
	{
		std::cout << "Usage : DiscoverNetwork merlin_bin IP.in router.out";
		std::cout << std::endl;	
	}
	else
	{
			
		switch ( fork() )
		{
			case -1 : 
				std::cout << "Error : fork() " << std::endl;
				return 0;
			case 0 : 
				/* Son execution */
				//execl(argv[1], "merlinc", argv[2], argv[3], (char *)NULL);
				perror("execl");
		sleep(1);
				return 0;
			default :
				/* Father execution */
				break;
		}
		
		int status;
		wait(&status);
		
		if (WIFSIGNALED(status))
		{		
			std::cout << "Merlin didn't end properly with signal " 
			<< WTERMSIG(status) << " (" << sys_siglist[WTERMSIG(status)] 
			<< ")" << std::endl;
			return 0;
		}
		
		else if (WIFSTOPPED(status))
		{
			std::cout << "Merlin didn't stop properly with signal " 
			<< WSTOPSIG(status) << " (" << sys_siglist[WSTOPSIG(status)] 
			<< ")" << std::endl;
			return 0;
		}
		else if (WIFEXITED(status))
			std::cout << "Merlin end properly" << std::endl;
		
		if (read_merlin_file(argv[3]))
		{
			complete_graph();

			print_graph();
			std::cout << "nb : " << router_vector.size() << std::endl;
			std::list<Router::RouterPath> tmp = router_vector.at(0)->get_all_paths(router_vector.at(5));
			//tmp.front().print_path();
				
			if(write_scamper_file(SCAMPER_DEFAULT_FILEIN_NAME))
			{
				/* Scamper treatment */
				std::cout << "scamper file OK " << std::endl;
				switch ( fork() )
				{
					case -1 : 
						std::cout << "Error : fork() " << std::endl;
						return 0;
					case 0 : 
						/* Son execution */
						std::cout << "Scamper is running ..." << std::endl;
						execlp("scamper", "scamper", /*"-O", "warts", "-o", 
							SCAMPER_DEFAULT_FILEOUT_NAME, */"-c", "tracelb -f 4", "-f",
							SCAMPER_DEFAULT_FILEIN_NAME, (char *)NULL);
						return 0;
					default :
						/* Father execution */
					break;
				}

				wait(&status);
		
				if (WIFSIGNALED(status))
				{		
					std::cout << "Scamper didn't end properly with signal " 
					<< WTERMSIG(status) << " (" << sys_siglist[WTERMSIG(status)] 
					<< ")" << std::endl;
					return 0;
				}
		
				else if (WIFSTOPPED(status))
				{
					std::cout << "Scamper didn't stop properly with signal " 
					<< WSTOPSIG(status) << " (" << sys_siglist[WSTOPSIG(status)] 
					<< ")" << std::endl;
					return 0;
				}
				else if (WIFEXITED(status))
					std::cout << "Scamper end properly" << std::endl;
				

			}
					
			else
					std::cout << "BUG" << std::endl;
		}
		else
			std::cout << "Error : file not found" << std::endl;

		clean_router_vector ();
	}		

	return 0;
}
